package com.gulimall.order.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.gulimall.common.constrant.AuthServerConstant;
import com.gulimall.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author kkk
 * @date 2022/8/3
 */
@Component
public class OrderInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<MemberRespVo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //过滤
        String requestURI = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/order/order/status/**", requestURI);
        boolean orderNotifyMatch = new AntPathMatcher().match("/payed/notify", requestURI);
        if (match || orderNotifyMatch) {
            return true;
        }

        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_INFO);
        MemberRespVo memberRespVo = attribute == null ? null :
                JSONObject.parseObject(JSONObject.toJSONString(attribute), MemberRespVo.class);
        if (memberRespVo == null) {
            session.setAttribute("msg", "请先登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        } else {
            THREAD_LOCAL.set(memberRespVo);

            return true;
        }
    }
}
